//
//  HMStatusViewModel.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 一个HMStatusViewModel包含一个微博模型
class HMStatusViewModel: NSObject {
    // MARK: - 属性
    /// 微博模型
    var status: HMStatus
    
    /// 视图模型提供 认证类型的图片
    var verifiedImage: UIImage?
    
    /// 视图模型提供 会员等级的图片
    var mbrankImage: UIImage?
    
    /// 原创微博配图的URL数组
    var storePictureURLs: [URL]?
    
    /// 被转发微博配图的URL数组
    var retweetStorePictureURLs: [URL]?
    
    /// 是否有被转发微博
    var isRetweetStatus: Bool = false
    
    /// 微博日期描述
    var sinaDateDescription: String?
    
    /// 微博来源
    var statusSource: String?
    
    /// 行高
    var rowHeight: CGFloat = 0
    
    /// 配图高度
    var pictureViewSize = CGSize()
    
    /// 被转发微博文本
    var retweetStatusText: String?
    
    /// 原创微博带表情的文本
    var originalAttrText: NSAttributedString?
    
    /// 被转发微博带表情的文本
    var retweetAttrText: NSAttributedString?
    
    // MARK: - 构造函数
    init(status: HMStatus) {
        self.status = status
        
        // 被转发微博内容
        let retweetText = status.retweeted_status?.text ?? "被转发微博内容为空"
        let retweetName = status.retweeted_status?.user?.name ?? "被转发微博用户名称"
        retweetStatusText = "@\(retweetName): \(retweetText)"
        
        originalAttrText = HMEmoticonManager.shared.emoticonAttrText(withString: status.text ?? "")
        retweetAttrText = HMEmoticonManager.shared.emoticonAttrText(withString: retweetStatusText ?? "")
        
        // 设置是否有被转发微博
        isRetweetStatus = status.retweeted_status != nil
        
        // 微博日期描述
        sinaDateDescription = Date.dateDescription(fromSinaDateString: status.created_at ?? "一万年")
        
        /// 微博来源
        // 当KVC设置来源:<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>
        if let source = status.source,
            source.characters.count > 0 {
            let nsSource = source as NSString
            
            let firstRange = nsSource.range(of: ">")
            let secondRnage = nsSource.range(of: "</")
            print("firstRange: \(firstRange.location), \(firstRange.length), secondRnage: \(secondRnage.location), \(secondRnage.length)")
            
            let range = NSRange(location: firstRange.location + 1, length: secondRnage.location - firstRange.location - 1)

            let newSource = nsSource.substring(with: range)
            statusSource = "来自 \(newSource)"
        } else {
            statusSource = "未知来源"
        }
        
        // 认证类型
        let verified_type = status.user?.verified_type ?? -1
        // verified_type 没有认证:-1   认证用户:0  企业认证:2,3,5  达人:220
        switch verified_type {
        case 0:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            // 其他情况
            verifiedImage = nil
        }
        
        // 会员等级
        let mbrank = status.user?.mbrank ?? 0
        // 会员等级 1-6
        // kvc设置会员等级的,知道自己是几级,就创建对应的图片
        if mbrank > 0 && mbrank <= 6 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        } else {
            mbrankImage = nil
        }
        
        // 原创微博配图URL数组
        let count = status.pic_urls?.count ?? 0
        if count > 0 {
            // 原创微博有图片,创建数组保存转好的URL
            storePictureURLs = [URL]()
            
            // 遍历所有字典
            for dict in status.pic_urls! {
                // 取出字典的value,转成URL,
                let urlString = dict["thumbnail_pic"]
                
                // 转成URL
                let url = URL(string: urlString!)!
                
                // 添加到storePictureURLs数组
                storePictureURLs?.append(url)
            }
        }
        
        // 被转发微博配图URL数组
        let retweetCount = status.retweeted_status?.pic_urls?.count ?? 0
        if retweetCount > 0 {
            // 原创微博有图片,创建数组保存转好的URL
            retweetStorePictureURLs = [URL]()
            
            // 遍历所有字典
            for dict in status.retweeted_status!.pic_urls! {
                // 取出字典的value,转成URL,
                var urlString = dict["thumbnail_pic"]
                urlString = urlString?.replacingOccurrences(of: "/thumbnail/", with: "/wap360/")
                
                // 转成URL
                let url = URL(string: urlString!)!
                
                // 添加到retweetStorePictureURLs数组
                retweetStorePictureURLs?.append(url)
            }
        }
        
        super.init()
        
        calcRowHeight()
    }
    
    func calcRowHeight() {
        // cell顶部间距高度(10) + 头像顶部间距(8) + 头像高度(35) + 文字顶部高度(8) + 文字高度(?)
        // 原创微博: + 配图高度(?)
        // 被转发微博: + 被转发文字顶部(8) + 被转发文字(?) + 被转发配图高度(?)
        // 配图底部(8)
        // 底部按钮高度
        
        var height = 10 + HMStatusCellMargin + 35 + HMStatusCellMargin
        
        let maxSize = CGSize(width: UIScreen.width - 2 * HMStatusCellMargin, height: CGFloat(MAXFLOAT))
        
        // 文字高度
        if let originalAttrText = originalAttrText {
            
            height += originalAttrText.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil).height
        }
        
        if isRetweetStatus {
            height += HMStatusCellMargin
            
            if let retweetAttrText = retweetAttrText {
                
                height += retweetAttrText.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil).height
                
                let count = retweetStorePictureURLs?.count ?? 0
                if count > 0 {
                    pictureViewSize = calcPictureViewSize(count: count)
                    height += pictureViewSize.height
                }
            }
        } else {
            // 是否有配图
            let count = storePictureURLs?.count ?? 0
            if count > 0 {
                pictureViewSize = calcPictureViewSize(count: count)
                height += pictureViewSize.height
            }
        }
        
        height += HMStatusCellMargin
        height += 38
        
        self.rowHeight = height
    }
    
    /// 计算配图的总宽和高
    ///
    /// - parameter count: 图片的数量
    ///
    /// - returns: 配图的总宽和高
    private func calcPictureViewSize(count: Int) -> CGSize {
        // 根据 图片数量 计算配图的总大小
        if count == 0 {
            return CGSize.zero
        }
        
        /// 默认3列
        var numberOfColumn = 3
        if count == 1 {
            // 只有一个图片,显示1列
            numberOfColumn = 1
        } else if count == 2 || count == 4 {
            // 2个或4个图片显示2列
            numberOfColumn = 2
        }
        
        // 计算宽度 = 总列数 * 图片的宽度 + (总列数 - 1) * 图片间距
        let width = CGFloat(numberOfColumn) * HMStatusPictureViewItemWH + (CGFloat(numberOfColumn) - 1) * HMStatusPictureViewItemMargin
        
        // 2 = (6 + 3 - 1) / 3
        // 3 = (9 + 3 - 1) / 3
        // 1 = (3 + 3 - 1) / 3
        // 总行数 = (总数 + 总列数 - 1) / 总列数, 前提保证都是整数
        let numberOfRow = (count + numberOfColumn - 1) / numberOfColumn
        
        // 计算高度 = 顶部间距 + 总行数 * 图片高度 + (总行数 - 1) * 图片的间距
        let height = HMStatusCellMargin + CGFloat(numberOfRow) * HMStatusPictureViewItemWH + (CGFloat(numberOfRow) - 1) * HMStatusPictureViewItemMargin
        
        return CGSize(width: width, height: height)
    }
    
    override var description: String {
        return "\(dictionaryWithValues(forKeys: ["status"]))"
    }
}
